<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <!--<div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
        </a-row>
      </a-form>
    </div>-->
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
      <a-button @click="handleAddSub" type="primary" style="float:right;" icon="plus">新增模板</a-button>
    </div>

    <!-- table区域-begin -->
    <div style="display:flex;">
      <div style="width:260px;border-top:solid 1px #eeeeee;border-left:solid 1px #eeeeee;border-right:solid 1px #eeeeee;">
        <draggable :list="dataSource" :options="{group:'title', animation:150}" @end="end">
          <div class="m-item" @click="selectIndex(index)" :class="s_index==index?'act':''" v-for="(item, index) in dataSource" :key="index"
            :index="index + ''">
            <div style="flex:1;">
              <div style="font-weight:600;line-height:18px;">{{item.name}}(编码:{{item.positionCode}})</div>
              <div style="font-size:12px;line-height:16px;color:#777777;">{{item.isIndex==1 ? "首页显示" : "普通模板"}}</div>
            </div>
            <a @click="handleEdit(item)">编辑</a>
            <a style="margin-left:10px;" v-if="item.positionCode!='1'" @click="handleDelete(item)">删除</a>
          </div>
        </draggable>
      </div>

      <div style="flex:1;padding-left:15px;">
        <div class="template-wrapper">
          <div style="overflow:hidden;">
            <div v-for="(item, index) in list" :key="index" style="width:224px;float:left;margin-right:10px;">
              <div class="template-item">
                <div class="template-item-img">
                  <div class="title">{{ item.title }}</div>
                </div>
                <div class="template-item-content">
                  <div class="title">{{ item.title }}</div>
                  <div class="btn-group">
                    <a-button-group>
                      <a-button size="small" type="danger" @click="handleDeleteSub(item.id,item.isEnable == 1)">删除</a-button>
                      <a-button v-if="item.isEnable == 0" size="small" @click="handleSet(item)">启用</a-button>
                      <a-button v-if="item.isEnable == 1" type="success" size="small" disabled>已启用</a-button>
                      <a-button size="small" @click="handleEditSub(item)">编辑</a-button>
                    </a-button-group>

                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <cms-floor-position-modal ref="modalForm" @ok="modalFormOk"></cms-floor-position-modal>
    <cms-floor-modal ref="modalFormSub" @ok="modalFormOk"></cms-floor-modal>
  </a-card>
</template>

<script>
import { filterObj } from '@/utils/util'
import { deleteAction, getAction, postAction, putAction, downFile, getFileAccessHttpUrl } from '@/api/manage'
import Vue from 'vue'
import draggable from 'vuedraggable'
import { ACCESS_TOKEN } from "@/store/mutation-types"
import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import CmsFloorPositionModal from './modules/CmsFloorPositionModal'
import CmsFloorModal from './modules/CmsFloorModal'

export default {
  name: 'CmsFloorPositionList',
  mixins: [mixinDevice],
  components: {
    draggable,
    CmsFloorPositionModal,
    CmsFloorModal
  },
  data () {
    return {
      description: '装修列表',
      // 表头
      columns: [
        {
          title: '装修页名称',
          align: "left",
          dataIndex: 'name',
          scopedSlots: { customRender: 'tplInfo' }
        },
        {
          title: '操作',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' }
        }
      ],
      url: {
        list: "/common/cmsFloorPosition/list",
        delete: "/common/cmsFloorPosition/delete",
        deleteSub: "/common/cmsFloor/delete",
        deleteBatch: "/common/cmsFloorPosition/deleteBatch",
        exportXlsUrl: "/common/cmsFloorPosition/exportXls",
        importExcelUrl: "common/cmsFloorPosition/importExcel",

      },
      dictOptions: {},
      //token header
      tokenHeader: { 'X-Access-Token': Vue.ls.get(ACCESS_TOKEN) },
      /* 查询条件-请不要在queryParam中声明非字符串值的属性 */
      queryParam: {},
      /* 数据源 */
      dataSource: [],
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + "-" + range[1] + " 共" + total + "条"
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      /* 排序参数 */
      isorter: {
        column: 'createTime',
        order: 'desc',
      },
      /* 筛选参数 */
      filters: {},
      /* table加载状态 */
      loading: false,
      /* table选中keys*/
      selectedRowKeys: [],
      /* table选中records*/
      selectionRows: [],
      /* 查询折叠 */
      toggleSearchStatus: false,
      /* 高级查询条件生效状态 */
      superQueryFlag: false,
      /* 高级查询条件 */
      superQueryParams: '',
      /** 高级查询拼接方式 */
      superQueryMatchType: 'and',
      /** 弹框参照专用 */
      visible: false,
      s_index: 0,
      list: []
    }
  },
  created () {
    this.loadData()
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  methods: {
    end (evt) {
      this.drag = true
      let id = ''
      let sort = 0
      if (evt.newIndex == 0) {
        sort = this.dataSource[1].sort - 10000
        id = this.dataSource[0].id
      } else if (evt.newIndex == this.dataSource.length - 1) {
        sort = this.dataSource[evt.newIndex - 1].sort + 10000
        id = this.dataSource[evt.newIndex].id
      } else {
        sort = parseInt((this.dataSource[evt.newIndex - 1].sort + this.dataSource[evt.newIndex + 1].sort) / 2)

        id = this.dataSource[evt.newIndex].id
      }
      putAction('/common/cmsFloorPosition/edit', {
        sort: sort,
        id: id
      }).then((res) => {

      })
    },
    loadData (arg) {
      if (!this.url.list) {
        this.$message.error("请设置url.list属性!")
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      this.isorter.column = "sort"
      this.isorter.order = "asc"
      var params = this.getQueryParams()//查询条件
      this.loading = true
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          this.dataSource = res.result.records
          this.ipagination.total = res.result.total
          this.list = res.result.records[this.s_index].cmsFloorList
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        this.loading = false
      })
    },
    selectIndex (index) {
      this.s_index = index
      this.list = this.dataSource[index].cmsFloorList
    },
    initDictConfig () {
      console.log("--这是一个假的方法!")
    },
    handleSuperQuery (params, matchType) {
      //高级查询方法
      if (!params) {
        this.superQueryParams = ''
        this.superQueryFlag = false
      } else {
        this.superQueryFlag = true
        this.superQueryParams = JSON.stringify(params)
        this.superQueryMatchType = matchType
      }
      this.loadData(1)
    },
    getQueryParams () {
      //获取查询条件
      let sqp = {}
      if (this.superQueryParams) {
        sqp['superQueryParams'] = encodeURI(this.superQueryParams)
        sqp['superQueryMatchType'] = this.superQueryMatchType
      }
      var param = Object.assign(sqp, this.queryParam, this.isorter, this.filters)
      param.field = this.getQueryField()
      param.pageNo = this.ipagination.current
      param.pageSize = this.ipagination.pageSize
      return filterObj(param)
    },
    getQueryField () {
      //TODO 字段权限控制
      var str = "id,"
      this.columns.forEach(function (value) {
        str += "," + value.dataIndex
      })
      return str
    },

    onSelectChange (selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },
    onClearSelected () {
      this.selectedRowKeys = []
      this.selectionRows = []
    },
    searchQuery () {
      this.loadData(1)
    },
    superQuery () {
      this.$refs.superQueryModal.show()
    },
    searchReset () {
      this.queryParam = {}
      this.loadData(1)
    },
    batchDel: function () {
      if (!this.url.deleteBatch) {
        this.$message.error("请设置url.deleteBatch属性!")
        return
      }
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！')
        return
      } else {
        var ids = ""
        for (var a = 0; a < this.selectedRowKeys.length; a++) {
          ids += this.selectedRowKeys[a] + ","
        }
        var that = this
        this.$confirm({
          title: "确认删除",
          content: "是否删除选中数据?",
          onOk: function () {
            that.loading = true
            deleteAction(that.url.deleteBatch, { ids: ids }).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.loadData()
                that.onClearSelected()
              } else {
                that.$message.warning(res.message)
              }
            }).finally(() => {
              that.loading = false
            })
          }
        })
      }
    },
    handleDelete: function (item) {
      if (item.positionCode == 1) {
        this.$message.warning('首页装修页!')
        return
      }
      if (!this.url.delete) {
        this.$message.error("请设置url.delete属性!")
        return
      }
      var that = this
      that.$confirm({
        title: '操作提醒',
        content: '确定要删除吗?',
        onOk () {
          deleteAction(that.url.delete, { id: item.id }).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.loadData()
            } else {
              that.$message.warning(res.message)
            }
          })
        },
        onCancel () {
          // console.log('Cancel')
        }
      })

    },
    handleEdit: function (record) {
      this.$refs.modalForm.edit(record)
      this.$refs.modalForm.title = "编辑"
      this.$refs.modalForm.disableSubmit = false
    },
    handleAdd: function () {
      this.$refs.modalForm.add()
      this.$refs.modalForm.title = "新增"
      this.$refs.modalForm.disableSubmit = false
    },
    handleTableChange (pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      //TODO 筛选
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = "ascend" == sorter.order ? "asc" : "desc"
      }
      this.ipagination = pagination
      this.loadData()
    },
    handleToggleSearch () {
      this.toggleSearchStatus = !this.toggleSearchStatus
    },
    // 给popup查询使用(查询区域不支持回填多个字段，限制只返回一个字段)
    getPopupField (fields) {
      return fields.split(',')[0]
    },
    modalFormOk () {
      // 新增/修改 成功时，重载列表
      this.loadData()
    },

    handleDeleteSub: function (id, isEnable) {
      if (isEnable) {
        this.$message.warning('已启用模板不能删除!')
        return
      }
      if (this.dataSource[this.s_index].positionCode == 1 && this.list.length == 1) {
        this.$message.warning('首页模板不能全部删除!')
        return
      }
      if (!this.url.deleteSub) {
        this.$message.error("请设置url.delete属性!")
        return
      }
      var that = this
      that.$confirm({
        title: '操作提醒',
        content: '确定要删除吗?',
        onOk () {
          deleteAction(that.url.deleteSub, { id: id }).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.loadData()
            } else {
              that.$message.warning(res.message)
            }
          })
        },
        onCancel () {
          // console.log('Cancel')
        }
      })

    },
    handleEditSub: function (record) {
      this.$router.push({ path: '/floor/floor/CmsFloorEdit', query: { id: record.id } })
    },
    handleAddSub: function () {


      this.$refs.modalFormSub.edit({
        positionCode: this.dataSource[this.s_index].positionCode,
        title: '',
        remark: '',
        isEnable: 0
      })
      this.$refs.modalFormSub.title = "新增"
      this.$refs.modalFormSub.disableSubmit = false
    },
    // 启用
    handleSet (item) {
      const that = this
      putAction('/common/cmsFloor/set-enable', { id: item.id, positionCode: item.positionCode }).then((res) => {
        if (res.success) {
          that.$message.success(res.message)
          that.loadData()
        } else {
          that.$message.warning(res.message)
        }
      })
    },



  }
}
</script>
<style scoped lang="less">
@import '~@assets/less/common.less';
.m-item {
  display: flex;
  line-height: 34px;
  padding: 8px 12px;
  border-bottom: solid 1px #eeeeee;
  border-right: 3px solid #ffffff;
}
.m-item:hover {
  display: flex;
  line-height: 34px;
  padding: 8px 12px;
  border-bottom: solid 1px #eeeeee;
  background-color: #e6f7ff;
  border-right: 3px solid #1890ff;
}
.act {
  background-color: #e6f7ff;
  border-right: 3px solid #1890ff;
}
.template-wrapper {
  padding: 0px 50px 20px 0;
  .template-item {
    position: relative;
    margin-bottom: 30px;
    width: 100%;
    height: 0;
    padding-top: 150%;
    background-color: #fff;
    border: solid 1px #f4f4f4;
    &-img {
      position: absolute;
      top: 5px;
      left: 5px;
      width: 214px;
      padding-top: 224px;
      background-repeat: no-repeat;
      background-size: cover;
      background-position: 0 0;
      background-color: ghostwhite;
      .title {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translateX(-50%);
        font-size: 15px;
      }
    }
    &-content {
      position: absolute;
      bottom: 0;
      width: 95%;
      left: 50%;
      transform: translateX(-50%);
      .title {
        margin-left: 5px;
        font-size: 14px;
      }
      .btn-group {
        display: flex;
        justify-content: flex-end;
        margin: 30px 0 10px;
      }
    }
    &:hover {
      animation: 0.3s 50 linear;
      border: solid 1px #1890ff;
    }
  }
  @keyframes play {
    50% {
      transform: translateY(-25px);
    }
    100% {
      transform: translateY(-25px);
    }
  }
}
</style>
